package com.cy.comstore.controller;

import com.cy.comstore.entity.Address;
import com.cy.comstore.service.IAddressService;
import com.cy.comstore.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("addresses")
public class AddressController extends BaseController{
    @Autowired
    private IAddressService addressService;

    @RequestMapping("addAddr")
    public JsonResult<Void> addNewAddr(Address address, HttpSession session){
        addressService.addNewAddress(getUidFromSession(session),getUsernameFromSession(session),address);
        return new JsonResult<>(OK);
    }

    //前端不传参就是用getmapping
    @GetMapping({"", "/"})
    public JsonResult<List<Address>> getByUid(HttpSession session) {
        Integer uid = getUidFromSession(session);
        List<Address> data = addressService.getByUid(uid);
        return new JsonResult<List<Address>>(OK, data);
    }

    @RequestMapping("/{aid}/delete")
    public JsonResult<Void> delete(@PathVariable Integer aid,HttpSession httpSession){
        addressService.delete(aid,getUidFromSession(httpSession),getUsernameFromSession(httpSession));
        return new JsonResult<>(OK);
    }

    @RequestMapping("/{aid}/set_default")
    public JsonResult<Void> setDefault(@PathVariable Integer aid,HttpSession httpSession){
        addressService.setDefault(aid,getUidFromSession(httpSession),getUsernameFromSession(httpSession));
        return new JsonResult<>(OK);
    }
}
